#include "delay.h"

static uint32_t fac_us=0;							//us延时倍数

void delay_init(uint8_t SYSCLK)
{
   HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);//SysTick为HCLK
   fac_us=SYSCLK;
}

void delay_us(uint32_t nus)
{
  uint32_t ticks;
	uint32_t told,tnow,tcnt=0;
	uint32_t reload=SysTick->LOAD;	//LOAD的值    	 
	ticks=nus*fac_us; 				//节拍数
	told=SysTick->VAL;        		//刚进入的计数器值
	while(1)
	{
		tnow=SysTick->VAL;	
		if(tnow!=told)
		{	    
			if(tnow<told)tcnt+=told-tnow;
			else tcnt+=reload-tnow+told;	    
			told=tnow;
			if(tcnt>=ticks)break;			//超出/等于延时时间退出
		}  
	};
}

void delay_ms(uint16_t nms)
{
  uint32_t i;
	for(i=0;i<nms;i++) delay_us(1000);
}

